package cn.iocoder.yudao.framework.redis.core;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.redis.core.model.BaseRedisEvent;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

/**
 * 监听redis事件
 *
 * @author: wds_prc
 * @since: 2024/8/2 17:07
 */
@Slf4j
public class RedisEventListener implements MessageListener {

    private ApplicationContext context;

    public RedisEventListener(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        final String body = message.toString();
        log.info("收到Redis发布的事件: {}", body);

        //SpringRedisEvent event = new SpringRedisEvent(this, body);

        final BaseRedisEvent baseEvent = JSON.parseObject(body, BaseRedisEvent.class);
        final String eventId = baseEvent.getEventId();

        try {
            final Class<?> eventClazz = Class.forName(eventId);
            final Object bizEvent = JsonUtils.parseObject(body, eventClazz);
            log.info("发送SpringEvent: {}", eventClazz.getName());
            context.publishEvent(bizEvent);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
